<script setup>
import Header from './components/FrontPage/header.vue'
import HeaderDiff from './components/FrontPage/headerDiff.vue'
import Menu from './components/FrontPage/menu.vue'
import Footer from './components/FrontPage/footerhome.vue'
import TopNavBar from '@/components/common/TopNavBar.vue'
import InfoPopup from '@/views/home/components/InfoPopup.vue' // ✅ 新增
import { getInfo, haveRead } from '@/api/info' // ✅ 新增
import { DIFF_HOME_BANNER } from '@/config/index'
import { useMainStore } from '@/store/index.js'
import { useUserStore } from '@/store/user/index'
import { getAcount } from '@/plugin/chain'
import { useRouter } from 'vue-router'
import { computed, ref, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { showToast } from 'vant'

const mainStore = useMainStore()
const userStore = useUserStore()
const isSign = computed(() => userStore.isSign)
const router = useRouter()
const { t } = useI18n()

// ✅ UID 显示为前2后2，中间****
const maskedUserId = computed(() => {
  const user = userStore.userInfo.user
  if (!user || !user.mdKey) return ''
  const key = String(user.mdKey)
  if (key.length <= 4) return key
  return key.substring(0, 2) + '****' + key.substring(key.length - 2)
})

// ✅ 点击 UID 复制完整 mdKey
const copyUserId = async () => {
  const user = userStore.userInfo.user
  if (!user || !user.mdKey) return showToast('no_data')
  try {
    await navigator.clipboard.writeText(user.mdKey)
    showToast('copy_success')
  } catch (err) {
    console.error('复制失败:', err)
    showToast('copy_error')
  }
}

onMounted(() => {
  mainStore.getSettingConfig()
  getUserMessages() // ✅ 新增：检测消息弹窗
})

// 钱包弹窗状态
const showWalletPopup = ref(false)
const openWalletPopup = () => {
  showWalletPopup.value = true
}

// 点击钱包连接
const connectWallet = async (type) => {
  try {
    showWalletPopup.value = false
    await getAcount(type)
  } catch (e) {
    console.error('connectWallet error:', e)
  }
}

// 登录跳转
const goSignIn = () => {
  router.push('/sign-in')
}

/* ============================ ✅ 新增：1对1弹窗逻辑 ============================ */
const showInfoPopup = ref(false)
const infoData = ref([])

// 获取站内信信息
const getUserMessages = async () => {
  if (!isSign.value) return
  try {
    const res = await getInfo()
    if (res.code === 200 && res.rows?.length) {
      infoData.value = res.rows
      showInfoPopup.value = true
    }
  } catch (err) {
    console.error('获取站内信失败:', err)
  }
}

// 关闭弹窗并标记已读
const closeInfoPopup = async () => {
  showInfoPopup.value = false
  const ids = infoData.value
    .filter((item) => item.type === '1')
    .map((item) => item.id)
  if (ids.length) {
    const params = `ids=${ids.join(',')}`
    await haveRead(params)
  }
}
</script>

<template>
  <!-- 顶部导航 -->
  <TopNavBar showImg="true">
    <template #right>
      <template v-if="!isSign">
        <button class="nav-btn" @click="openWalletPopup">
          Connect
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="14"
            height="14"
            viewBox="0 0 24 24"
            fill="none"
            stroke="black"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            style="margin-left: 6px;"
          >
            <path
              d="M15.5 12H3m12.5 0l-3.5 3.5M15.5 12l-3.5-3.5M21 19V5a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2z"
            />
          </svg>
        </button>
        <button class="nav-btn" @click="goSignIn">{{ _t18('login_account') }}</button>
      </template>

      <!-- ✅ 已登录：显示 UID（点击复制） -->
      <template v-else>
        <div class="nav-btn uid-box" @click="copyUserId">
          {{ maskedUserId }}
        </div>
      </template>
    </template>
  </TopNavBar>

  <!-- 页面主体 -->
  <div class="home-container">
    <Footer></Footer>
  </div>

  <!-- 悬浮客服按钮 -->
  <div class="global-float-btn" @click="$router.push('/service')">
    <img src="@/assets/img/Ki8_df270a6e_5CB.63a2943f.png" alt="float-icon" />
  </div>

  <!-- ✅ 钱包弹窗 -->
  <van-popup
    v-model:show="showWalletPopup"
    round
    closeable
    position="center"
    class="wallet-popup"
    :teleport="false"
  >
    <div class="wallet-popup-container">
      <h3>{{ _t18('27_lianjieqianbao') }}</h3>
      <p class="desc">
        {{ _t18('27_lianjieqianbao1') }}<br />
        {{ _t18('27_lianjieqianbao2') }}
      </p>

      <div class="wallet-list">
        <div
          v-for="item in [
            { name: 'Coinbase', icon: '/static/img/coinbase.png', type: 'coinbase' },
            { name: 'OnChain', icon: '/static/img/crypto.png', type: 'onchain' },
            { name: 'Trust', icon: '/static/img/trust-5AGI7VnG.png', type: 'trust' },
            { name: 'MetaMask', icon: '/static/img/metamask-DncXFm7-.png', type: 'metamask' }
          ]"
          :key="item.type"
          class="wallet-item"
          @click="connectWallet(item.type)"
        >
          <img :src="item.icon" alt="wallet" />
          <span>{{ item.name }}</span>
        </div>
      </div>
    </div>
  </van-popup>

  <!-- ✅ 站内信弹窗（1对1消息） -->
  <InfoPopup :show="showInfoPopup" :data="infoData" @closeBtn="closeInfoPopup" />
</template>

<style scoped>
.home-container {
  min-height: 100vh;
  background: #f4f6f8;
  padding-bottom: 80px;
  overflow-y: auto;
}

/* 悬浮按钮 */
.global-float-btn {
  position: fixed;
  right: 20px;
  bottom: 100px;
  z-index: 2001;
  width: 56px;
  height: 56px;
  border-radius: 50%;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border: none;
  transition: box-shadow 0.2s, transform 0.2s;
}
.global-float-btn img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
.global-float-btn:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.22);
  transform: translateY(-2px) scale(1.05);
}

/* 按钮样式 */
.nav-btn {
  border: 1px solid #222;
  background: #fff;
  border-radius: 24px;
  padding: 0 16px;
  height: 33px;
  margin-left: 8px;
  font-size: 13px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s;
}

/* ✅ UID hover 提示点击复制 */
.uid-box {
  user-select: none;
}
.uid-box:hover {
  background: #f5f5f5;
}

/* 钱包弹窗 */
.wallet-popup {
  width: 340px;
  padding: 24px 20px;
  background: #1b1d29;
  color: #fff;
  border-radius: 12px;
  z-index: 4000 !important;
}
.wallet-popup-container h3 {
  margin: 0;
  font-size: 20px;
  font-weight: bold;
  text-align: center;
}
.wallet-popup-container .desc {
  font-size: 13px;
  line-height: 20px;
  text-align: center;
  margin: 10px 0 20px;
  color: #ccc;
}
.wallet-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}
.wallet-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #2b2e42;
  border-radius: 10px;
  padding: 14px 0;
  transition: 0.2s;
  cursor: pointer;
}
.wallet-item:hover {
  background: #3a3f59;
  transform: translateY(-2px);
}
.wallet-item img {
  width: 40px;
  height: 40px;
  margin-bottom: 8px;
}
.wallet-item span {
  font-size: 13px;
}
@media (min-width: 668px) {
  .home-container {
    width: 350px;
    margin: 0 auto;
  }
}
</style>
